﻿using Core.DataAccess.Model.Project.Order;
using Core.Framework.Model.Common;
using Core.Framework.Model.WChat;
using Core.Framework.Util;
using Core.IBusiness.IOrderModule;
using Core.IBusiness.IProjectModule;
using Core.IBusiness.ISDK;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Core.Business.SDKService
{
    public class Pay : BaseHttpPipelineInfo,IPay
    {

        private IOrder iOrder { get; set; }
        private IProjectUserApiService iProjectUserApiService { get; set; }
        

        public Pay(IOrder order, IProjectUserApiService projectUserApiService, IHttpContextAccessor iHttp) : base(iHttp)
        {
            this.iOrder = order;
            this.iProjectUserApiService = projectUserApiService;
        }


        /// <summary>
        /// 支付宝电商订单
        /// </summary>
        /// <param name="orderKey">订单号</param>
        /// <param name="projectInfo">项目信息</param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal,string>> AliShopOrderPay(int orderKey, ApiProjectInfo projectInfo)
        {
            try
            {
                var result = this.GetOrderPaymentPrice(orderKey);

                if (!result.IsFinished)
                {
                    return result;
                }

                var price = result.Date.Key;

                if (price > 0)
                {
                    var tool = new Aop.Api.Tool();

                    var orderInfo = tool.AliPay(
                        orderKey.ToString(),
                        Math.Round(price, 2).ToString(),
                        "Itool" + orderKey + "-订单付款",
                        projectInfo.PayAliInfo.ApiUrl,
                        projectInfo.PayAliInfo.AppId,
                        projectInfo.PayAliInfo.Privtekey,
                        projectInfo.PayAliInfo.Publickey
                        );

                    return new MethodResult<KeyValuePair<decimal, string>> {
                        Date = new KeyValuePair<decimal, string>(price,orderInfo),
                        IsFinished = true
                    };
                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>> {
                        IsFinished = false,
                        Discription = "订单需付款金额为0"
                    };
                }
            }
            catch (Exception e)
            {

                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        IsFinished = false,
                        Discription = e.Message
                    };
            }
            
        }

        /// <summary>
        /// 支付宝支付
        /// </summary>
        /// <param name="price">金额</param>
        /// <param name="title">订单名称</param>
        /// <param name="projectInfo">项目名称</param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal, string>> AliPay(decimal price, string title, ApiProjectInfo projectInfo)
        {
            try
            {
                if (price > 0)
                {
                    var tool = new Aop.Api.Tool();

                    var orderInfo = tool.AliPay(
                        DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(1000, 99999),
                        Math.Round(price, 2).ToString(),
                        title + " - 订单付款",
                        projectInfo.PayAliInfo.ApiUrl,
                        projectInfo.PayAliInfo.AppId,
                        projectInfo.PayAliInfo.Privtekey,
                        projectInfo.PayAliInfo.Publickey
                        );

                    return new MethodResult<KeyValuePair<decimal, string>> {
                        Date = new KeyValuePair<decimal, string>(price,orderInfo),
                        IsFinished = true };
                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>> { IsFinished = false, Discription = "订单需付款金额为0" };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<KeyValuePair<decimal, string>> { IsFinished = false, Discription = e.Message };
            }
        }

        /// <summary>
        /// 微信电商订单
        /// </summary>
        /// <param name="orderKey">订单号</param>
        /// <param name="projectInfo">项目信息</param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal, string>> WChatShopOrderPay(int orderKey, ApiProjectInfo projectInfo)
        {
            try
            {
                var result = this.GetOrderPaymentPrice(orderKey);

                if (!result.IsFinished)
                {
                    return result;
                }

                var price = result.Date.Key;

                if (price > 0)
                {

                    price = Math.Round(price, 2) * 100;

                    var tool = new SDK.WChatPay.AppPayTool(
                        projectInfo.PayWChatInfo.MchId,
                        projectInfo.PayWChatInfo.AppId,
                        projectInfo.PayWChatInfo.ApiKey,
                        projectInfo.PayWChatInfo.NotifyUrl
                        );

                    var orderInfo = tool.Pay((long)price, orderKey.ToString(), "订单付款", this.GetLocalIP());

                    if (null == orderInfo)
                    {
                        result.Date = default;
                        result.IsFinished = false;
                        result.Discription = "微信支付签名失败";
                    }
                    else
                    {
                        result.Date = new KeyValuePair<decimal, string>(price, orderInfo);
                    }

                    return result;
                }
                else
                {
                    result.Date = default;
                    result.IsFinished = false;
                    result.Discription = "订单需付款金额为0";

                    return result;
                }
            }
            catch (Exception e)
            {

                return new MethodResult<KeyValuePair<decimal, string>>
                {
                    IsFinished = false,
                    Discription = e.Message
                };
            }

        }

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="price">金额</param>
        /// <param name="title">订单名称</param>
        /// <param name="projectInfo">项目名称</param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal, string>> WChatPay(decimal price, string title, ApiProjectInfo projectInfo)
        {
            try
            {
                if (price > 0)
                {

                    price = Math.Round(price, 2) * 100;

                    var orderKey = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(1000, 99999);

                    var tool = new SDK.WChatPay.AppPayTool(
                        projectInfo.PayWChatInfo.MchId,
                        projectInfo.PayWChatInfo.AppId,
                        projectInfo.PayWChatInfo.ApiKey,
                        projectInfo.PayWChatInfo.NotifyUrl
                        );

                    var orderInfo = tool.Pay((long)price, "Itool" + orderKey + "-订单付款", title, this.GetLocalIP());

                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        Date = new KeyValuePair<decimal, string>(price, orderInfo),
                        IsFinished = true
                    };

                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>> { IsFinished = false, Discription = "订单需付款金额为0" };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<KeyValuePair<decimal, string>> { IsFinished = false, Discription = e.Message };
            }
        }



        /// <summary>
        /// 支付宝服务订单付款
        /// </summary>
        /// <param name="orderKey"></param>
        /// <param name="projectInfo"></param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal, string>> AliServiceOrderPay(string title,int orderKey, ApiProjectInfo projectInfo)
        {
            try
            {
                var result = this.iProjectUserApiService.GetOrder(orderKey);

                if (!result.IsFinished)
                {
                    return new MethodResult<KeyValuePair<decimal, string>> {
                        Date = new KeyValuePair<decimal, string>(0, result.Discription),
                        IsFinished = false
                    };
                }

                var price = (decimal)result.Date.ApiMoney;

                if (price > 0)
                {
                    var tool = new Aop.Api.Tool();

                    var orderInfo = tool.AliPay(
                        orderKey.ToString(),
                        Math.Round(price, 2).ToString(),
                        title,
                        projectInfo.PayAliInfo.ApiUrl,
                        projectInfo.PayAliInfo.AppId,
                        projectInfo.PayAliInfo.Privtekey,
                        projectInfo.PayAliInfo.Publickey
                        );

                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        Date = new KeyValuePair<decimal, string>(price, orderInfo),
                        IsFinished = true
                    };
                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        IsFinished = false,
                        Discription = "订单需付款金额为0"
                    };
                }
            }
            catch (Exception e)
            {

                return new MethodResult<KeyValuePair<decimal, string>>
                {
                    IsFinished = false,
                    Discription = e.Message
                };
            }

        }

        /// <summary>
        /// 微信服务订单付款
        /// </summary>
        /// <param name="orderKey"></param>
        /// <param name="projectInfo"></param>
        /// <returns></returns>
        public MethodResult<KeyValuePair<decimal, string>> WChatServiceOrderPay(string title, int orderKey, ApiProjectInfo projectInfo)
        {
            try
            {
                var result = this.iProjectUserApiService.GetOrder(orderKey);

                if (!result.IsFinished)
                {
                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        Date = new KeyValuePair<decimal, string>(0, result.Discription),
                        IsFinished = false
                    };
                }

                var price = (decimal)result.Date.ApiMoney;

                if (price > 0)
                {

                    price = Math.Round(price, 2) * 100;

                    var tool = new SDK.WChatPay.AppPayTool(
                        projectInfo.PayWChatInfo.MchId,
                        projectInfo.PayWChatInfo.AppId,
                        projectInfo.PayWChatInfo.ApiKey,
                        projectInfo.PayWChatInfo.NotifyUrl
                        );

                    var orderInfo = tool.Pay((long)price, orderKey.ToString(), title, this.GetLocalIP());

                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        Date = new KeyValuePair<decimal, string>(price, orderInfo),
                        IsFinished = true
                    };
                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        IsFinished = false,
                        Discription = "订单需付款金额为0"
                    };
                }
            }
            catch (Exception e)
            {

                return new MethodResult<KeyValuePair<decimal, string>>
                {
                    IsFinished = false,
                    Discription = e.Message
                };
            }

        }


        public MethodResult<KeyValuePair<decimal, string>> TransferByAccounts(string title,  ApiProjectInfo projectInfo)
        {
            try
            {

                var price = (decimal)1;

                if (price > 0)
                {
                    var tool = new Aop.Api.Tool();

                    var aliResult = tool.TransferByAccounts(
                        DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(1000, 99999),
                        Math.Round(price, 2).ToString(),
                        title,
                        projectInfo.PayAliInfo.ApiUrl,
                        projectInfo.PayAliInfo.AppId,
                        projectInfo.PayAliInfo.Privtekey,
                        projectInfo.PayAliInfo.Publickey
                        );

                    var jObject = aliResult.TryToJObject();
                    var jResult = jObject["alipay_fund_trans_toaccount_transfer_response"];

                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        Date = new KeyValuePair<decimal, string>(price, jResult.ToString()),
                        IsFinished = int.Parse(jResult["code"].ToString()) == 10000,
                        Discription = jResult["msg"].ToString()
                    };
                }
                else
                {
                    return new MethodResult<KeyValuePair<decimal, string>>
                    {
                        IsFinished = false,
                        Discription = "订单需付款金额为0"
                    };
                }
            }
            catch (Exception e)
            {

                return new MethodResult<KeyValuePair<decimal, string>>
                {
                    IsFinished = false,
                    Discription = e.Message
                };
            }

        }



        /// <summary>
        /// 获取订单支付金额
        /// </summary>
        /// <param name="orderKey"></param>
        /// <returns></returns>
        private MethodResult<KeyValuePair<decimal, string>> GetOrderPaymentPrice(int orderKey)
        {
            OrderBasis order = this.GetOrder(orderKey);

            if (null == order)
            {
                return new MethodResult<KeyValuePair<decimal, string>>
                {
                    IsFinished = false,
                    Discription = "订单信息不存在"
                };
            }

            var price = order.DiscountPrice - order.Payment;

            return new MethodResult<KeyValuePair<decimal, string>>
            {
                Date = new KeyValuePair<decimal, string>(price > 0 ? price:0, string.Empty),
                IsFinished = true
            };
        }

        /// <summary>
        /// 获取订单信息
        /// </summary>
        /// <param name="orderKey"></param>
        /// <returns></returns>
        private OrderBasis GetOrder(int orderKey)
        {
            using (var context = new ProjectOrderContext())
            {
                return context
                    .OrderBasis
                    .Where(a => a.OrderKey == orderKey)
                    .FirstOrDefault();
            }
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns>本机IP地址</returns>
        private string GetLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public MethodResult<MinWChatPayParameter> MinWChatShopOrderPay(int orderKey)
        {
            var result = new MethodResult<MinWChatPayParameter>();

            try
            {
                var resultOrder = this.GetOrderPaymentPrice(orderKey);


                if (!resultOrder.IsFinished)
                {
                    return new MethodResult<MinWChatPayParameter> { 
                        IsFinished = resultOrder.IsFinished,
                        Discription = resultOrder.Discription
                    };
                }

                var price = resultOrder.Date.Key;

                if (price > 0)
                {

                    price = Math.Round(price, 2) * 100;

                    var tool = new SDK.WChatPay.MinPayTool(
                        this.iProjectInfo.PayWChatInfo.MchId,
                        this.iProjectInfo.PayWChatInfo.MinAppId,
                        this.iProjectInfo.PayWChatInfo.ApiKey,
                        this.iProjectInfo.PayWChatInfo.NotifyUrl
                        );

                    var orderInfo = tool.Pay((long)price, orderKey.ToString(), "订单付款", this.GetLocalIP(),this.iClientInfo.MinOpenID);

                    if (null == orderInfo)
                    {
                        result.Date = default;
                        result.IsFinished = false;
                        result.Discription = "微信支付签名失败";
                    }
                    else
                    {
                        result.IsFinished = true;
                        result.Date = orderInfo;
                    }
                }
                else
                {
                    result.Date = default;
                    result.IsFinished = false;
                    result.Discription = "订单需付款金额为0";
                }
            }
            catch (Exception e)
            {
                result.Date = default;
                result.IsFinished = false;
                result.Discription = e.Message;
            }

            return result;

        }
    }
}
